package com.applink.sell_proof;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.broadcast_receiver.NetworkConnectivityReceiver;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.database.table.AnalyticDBHelper;
import com.applink.sell_proof.database.table.ClaimDBHelper;
import com.applink.sell_proof.database.table.ProjectDBHelper;
import com.applink.sell_proof.util.Utility;
import com.google.android.gcm.GCMRegistrar;

public class NewLogInActivity extends Activity implements Observer,
		OnClickListener {

	private Button btnLogin;
	private TextView btnForgetPass;
	private EditText edtUserId;
	private EditText edtPassword;
	private Context mContext;
	private String email = "";
	private String pass = "";
	private ProgressDialog processDialog;
	private static final int LOGIN = 0;
	private static final int LOGIN_OFFLINE = 1;
	// private boolean doubleBackToExitPressedOnce = false;
	private int heightDiff = 0;
	private Intent intent;
	// private static final int LOAD_DATA_SYNC_ONLINE = 0;
	public static final int LOAD_DATA_SYNC_OFFLINE = 1;
	private TextView txtVersion;
	// EMarketingDatabaseHelper mDatabaseHelper;
	public static int intervalTimeMinute;
	private String userName = "";
	private int flagLogin = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		mContext = this;
		initView();

		final View activityRootView = findViewById(R.id.relative_login);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						Rect r = new Rect();
						// r will be populated with the coordinates of your view
						// that area still visible.
						activityRootView.getWindowVisibleDisplayFrame(r);

						heightDiff = activityRootView.getRootView().getHeight()
								- (r.bottom - r.top);
						// if (heightDiff > 100) { // if more than 100 pixels,
						// its probably a keyboard...
						// }
					}
				});
	}

	private void initView() {
		if (EMarketing.getInstance().getAccountEmail() != null) {
			userName = EMarketing.getInstance().getAccountEmail();
		}
		processDialog = new ProgressDialog(this);
		if (txtVersion == null) {
			txtVersion = (TextView) findViewById(R.id.txt_version_name);
			try {
				String versionName = getPackageManager().getPackageInfo(
						getPackageName(), 0).versionName;
				txtVersion.setText("v." + versionName);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		}

		if (btnLogin == null) {
			btnLogin = (Button) findViewById(R.id.btn_login);
		}

		if (btnForgetPass == null) {
			btnForgetPass = (TextView) findViewById(R.id.forget_password);
		}

		if (edtUserId == null) {
			edtUserId = (EditText) findViewById(R.id.edt_user_id);
		}

		if (edtPassword == null) {
			edtPassword = (EditText) findViewById(R.id.edt_password);
		}

		try {
			intervalTimeMinute = Integer.parseInt(getResources().getString(
					R.string.intervalLoginTime));
		} catch (Exception e) {
			intervalTimeMinute = 30;
		}

		listener();
		checkUsername();
	}

	private void checkUsername() {
		if (userName.length() > 0) {
			edtUserId.setText(userName);
			edtUserId.setEnabled(false);
			edtUserId.setTextColor(mContext.getResources().getColor(
					R.color.gray));
		} else {
			edtUserId.setEnabled(true);
		}
	}

	private void listener() {
		btnLogin.setOnClickListener(this);
		btnForgetPass.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		DataHelper.getInstance().addObserver(this);
	}

	@Override
	public void update(Observable observable, Object data) {
		Utility.hideWaitingStatus(processDialog);
		if (data == null)
			return;
		DataResult result = (DataResult) data;
		if (result.getMethodName() == Methods.Login) {
			if (result.getErrorCode() == null) {
				int responseCode = (Integer) result.getData();

				if (responseCode == 0) {
					Utility.showAlertDialog(mContext,
							android.R.drawable.ic_dialog_alert, getResources()
									.getString(R.string.error_login),
							"Attention");
				} else if (responseCode == 1) {
					if (Constant.CHECK_ACCOUNT) {
						ClaimDBHelper.deleteDataClaim();
						ProjectDBHelper.deleteDataProject();
					}
					EMarketing.getInstance().setAccountEmail(
							edtUserId.getText().toString());

					String encryptedPassword = edtPassword.getText().toString();
					/*
					 * try { encryptedPassword = SimpleCrypto.encrypt("APLINK",
					 * edtPassword.getText().toString()); } catch (Exception e)
					 * { encryptedPassword = edtPassword.getText().toString(); }
					 */
					EMarketing.getInstance().setAccountPassword(
							encryptedPassword);
					Log.e("abc", "token "
							+ EMarketing.getInstance().getAccountToken());
					System.out.println(">>>> "
							+ EMarketing.getInstance().getContactID());
					DataHelper.getInstance().getUserSetting();
					DataHelper.getInstance().getAllCountry();
					final String regId = GCMRegistrar
							.getRegistrationId(getApplicationContext());

					if (EMarketing.getInstance().getCheckLog()) {
						// Utility.checkServerTimeOut = false;

						// this function is added when the user login
						// successfully by server (ONLINE), and make sure has
						// ServerTokenTimeout

						// REMOVE EMPTY TABLE IF THERE IS RETURNED A 1 CODE FROM
						// SERVER, AND OTHERWISE
						DataHelper.getInstance().updateUserActivity();
						EMarketing.getInstance().setCheckLog(false);

					}
					if (flagLogin == 0) {
						AnalyticDBHelper.tracked("Logged in");
						System.out.println("<<<<<<<<<<<<" + "Online");

						++flagLogin;
					}

					Utility.SyncData();
					if (regId.equals("")) {
						// Automatically registers application on startup.
						GCMRegistrar.register(getApplicationContext(),
								Config.GCM_SENDER_ID);
					}

					// startActivity(new Intent(mContext, ClaimActivity.class));
					startActivity(new Intent(mContext, LearnActivity.class));
					finish();
				} else if (responseCode == 2) {
					startActivity(new Intent(mContext, ChangePassword.class));

				} else {
					Utility.showAlertDialog(mContext,
							android.R.drawable.ic_dialog_alert, getResources()
									.getString(R.string.error_login),
							"Attention");
				}
			} else {
				Utility.showAlertDialog(mContext,
						android.R.drawable.ic_dialog_alert, getResources()
								.getString(R.string.error_login), "Attention");
			}
		}

		// if (result.getMethodName() == Methods.updateUserActivity) {
		//
		// }
	}

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			switch (arg0.what) {
			case LOGIN:
				Utility.showWaitingStatus(processDialog);
				DataHelper.getInstance().login(email, pass);
				break;

			case LOGIN_OFFLINE:
				Utility.showWaitingStatus(processDialog);
				String decryptPassword = EMarketing.getInstance()
						.getAccountPassword();
				System.out.println("Password = "
						+ EMarketing.getInstance().getAccountPassword());
				// try {
				// decryptPassword = SimpleCrypto.decrypt("APLINK",
				// EMarketing.getInstance().getAccountPassword());
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				// when the server token is wrong.
				if (decryptPassword.length() == 0) {
					Utility.hideWaitingStatus(processDialog);
					Utility.showDialogNetwork(mContext,
							android.R.drawable.ic_dialog_alert);
				} else if (email.equals(EMarketing.getInstance()
						.getAccountEmail()) && pass.equals(decryptPassword)) {
					EMarketing.getInstance().setLogin(true);
					loadDataSync(false);
					// Splash.getInstant.mHandler
					// .sendEmptyMessage(Splash.LOAD_DATA_SYNC_OFFLINE);

					// startActivity(new Intent(getActivity(),
					// AllProjectActivity.class));
					// getActivity().finish();
				} else {
					Utility.hideWaitingStatus(processDialog);
					Utility.showAlertDialog(mContext,
							android.R.drawable.ic_dialog_alert, getResources()
									.getString(R.string.error_login),
							"Attention");
				}
			default:
				break;
			}
			return false;
		}
	});

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.btn_login:
			email = edtUserId.getText().toString();
			pass = edtPassword.getText().toString();
			if (!EMarketing.isOnline()) {
				mHandler.sendEmptyMessage(LOGIN_OFFLINE);
			}

			else {
				mHandler.sendEmptyMessage(LOGIN);
			}
			break;
		case R.id.forget_password:
			Intent intLogin = new Intent(mContext, ForgotPassword.class);
			startActivity(intLogin);
			// (new ForgotPassword()).show(getSupportFragmentManager(),
			// ForgotPassword.TAG);
			// startActivity(new Intent(mContext, ChangePassword.class));
		default:
			break;
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (heightDiff < 100) {
				moveTaskToBack(true);
			}
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	private void loadDataSync(final boolean checkLogin) {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {

				final String regId = GCMRegistrar
						.getRegistrationId(getApplicationContext());

				// Automatically registers application on startup.
				if (regId.equals("") && EMarketing.getInstance().isLogin()) {
					GCMRegistrar.register(getApplicationContext(),
							Config.GCM_SENDER_ID);
				}
				// EMarketingContentProvider.
				// SQLiteDatabase db = helper.getWritableDatabase(); // helper
				// is object extends SQLiteOpenHelper
				// db.delete(DatabaseHelper.TAB_USERS, null, null);
				// SQLiteDatabase db = null;
				// db = mDatabaseHelper.getWritableDatabase();
				// db.delete(ClaimDBHelper.TABLE_NAME, null, null);

				return EMarketing.getInstance().isLogin();
			}

			@Override
			protected void onPostExecute(Boolean isLogin) {
				if (isLogin) {

					Utility.hideWaitingStatus(processDialog);
					// log that user is log in
					AnalyticDBHelper.tracked("Logged in");
					System.out.println("<<<<<<<<<<<<" + "Offline");
					// here we set local expire time

					Utility.setLocalTimeExpiry();

					// int currentTab = CustomerSupportHelper
					// .getInt(Constant.DEFAULT_TAB);
					int currentTab = 2;
					switch (currentTab) {
					case 0:
						intent = new Intent(getApplicationContext(),
								ClaimActivity.class);
						break;
					case 1:
						intent = new Intent(getApplicationContext(),
								RewardActivity.class);
						break;
					case 2:
						intent = new Intent(getApplicationContext(),
								LearnActivity.class);
						break;
					case 3:
						intent = new Intent(getApplicationContext(),
								LifeStyleActivity.class);
						break;
					case 4:
						intent = new Intent(getApplicationContext(),
								CustomerServiceActivity.class);
						break;
					default:
						intent = new Intent(getApplicationContext(),
								LearnActivity.class);
						break;
					}

					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							startActivity(intent);
							finish();
						}
					}, 500);

					Utility.SyncData();
					NetworkConnectivityReceiver.checkDataSync = true;
				} else {
					if (checkLogin) {
						passToLogin();
					}

				}

			}
		}.execute((Void) null);
	}

	public void passToLogin() {

		intent = new Intent(getApplicationContext(), NewLogInActivity.class);
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				startActivity(intent);
				finish();
				// DialogFragment login = new LogIn();
				// login.show(getSupportFragmentManager(), LogIn.TAG);
			}
		}, 500);
	}
}
